package com.ssm.crud.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.crud.bean.Employee;
import com.ssm.crud.bean.Msg;
import com.ssm.crud.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

/*
* 处理员工的CRUD请求
* @Author szj
* */
@Controller
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    /*
    * 导入jackson宝
    * */
    @ResponseBody
    @RequestMapping(value = "/EmploysForJson",method = RequestMethod.GET)
    public Msg getEmploysWithJson(@RequestParam(value = "pn",defaultValue = "1")Integer pn){
        //引用Mybatis PageHelper分页插件
        //查询之前需要调用,传入页码，以及每页的大小
        String orderBy="e.emp_id Desc";
        PageHelper.startPage(pn,5,orderBy);
        //startPage后面紧跟的这个查询就是一个分页查询
        List<Employee> employs = employeeService.getAll();
        //用PageInfo包装查询后的结果，只需要讲pageInfo交给界面就行了。
        //封装了详细的分页信息，包括有我们，查询出来的数据,传入连续显示的页数
        PageInfo pageInfo = new PageInfo(employs,5);

        return Msg.Success().add("PageInfo",pageInfo);
    }

    /**
     * 员工保存
     * 1、支持JSR303校验
     * 2、导入Hibernate-Validator
     * @param employee
     * @return
     */
    @RequestMapping(value = "/Employs",method = RequestMethod.POST)
    @ResponseBody
    public Msg SaveEmp(@Valid Employee employee, BindingResult result){
        Map map = new HashMap<String,String>();
        if (employee==null)
            return Msg.Fail();
        //校验用户名是否重复
        boolean flag = employeeService.checkUser(employee.getEmpName());
        if(!flag){
                map.put("empName","Jsr303 用户名重复");

            return Msg.Fail().add("errorFields",map);
        }
        List<FieldError>  errors = result.getFieldErrors();
        if (result.hasErrors()){
            //校验失败，应该返回失败，在模态框中显示校验失败的错误码信息
            for (FieldError error: errors) {
                System.out.println("错误的字段名"+error.getField());
                System.out.println("错误的提示信息"+error.getDefaultMessage());
                map.put(error.getField(),error.getDefaultMessage());
            }

        return Msg.Fail().add("errorFields",map);
        }else {
            employeeService.SaveEmp(employee);
        }

        return Msg.Success();
    }

    /*
    * 查询员工数据（分页查询）JSP
    * */
    @RequestMapping(value = "/Employs",method = RequestMethod.GET)
    public String getEmploys(@RequestParam(value = "pn",defaultValue = "1")Integer pn, Model model){
        //引用Mybatis PageHelper分页插件
        //查询之前需要调用,传入页码，以及每页的大小
        PageHelper.startPage(pn,5);
        //startPage后面紧跟的这个查询就是一个分页查询
        List<Employee> employs = employeeService.getAll();
        //用PageInfo包装查询后的结果，只需要讲pageInfo交给界面就行了。
        //封装了详细的分页信息，包括有我们，查询出来的数据,传入连续显示的页数
        PageInfo page = new PageInfo(employs,5);
        model.addAttribute("pageInfo",page);

        return "list";
    }

    /**
     * 检查用户名是否可用
     * @param empName
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/CheckUser",method = RequestMethod.GET)
    public Msg checkUser(String empName){
        //先判断用户名是否是合法的表达式;
        String regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})";
        if(!empName.matches(regx)){
            return new Msg().Fail().add("va_msg","后端：用户名可以是2-5位中文或者6-16英文和数字的组合");
        }

        boolean flag = employeeService.checkUser(empName);
        if(flag){
            return new Msg().Success().add("va_msg","后端：用户名可用");
        }

        return new Msg().Fail().add("va_msg","后端：用户名不可用");
    }

    /**
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/emp/{id}",method = RequestMethod.GET)
    @ResponseBody
    public Msg getEmp(@PathVariable("id") String id){
        Employee employee = employeeService.getEmp(id);

        return Msg.Success().add("emp",employee);
    }

    /**
     *
     * @param employee
     * @return
     */
    @RequestMapping(value = "/emp/{empId}/{empName}",method = RequestMethod.PUT)
    @ResponseBody
    public Msg SaveEmp(Employee employee, HttpServletRequest request){
        employeeService.updateEmp(employee);

        return Msg.Success().add("emp",employee);
    }


    /**
     * 单个删除 或者批量删除
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/emp/{empId}",method = RequestMethod.DELETE)
    public Msg deleteEmp(@PathVariable("empId")String ids){
        //批量删除
        if (ids.contains("-")){
            List<Integer> del_ids = new ArrayList<>();
            String[] str_ids = ids.split("-");
            //组装id的集合
            for (String id: str_ids){
                del_ids.add(Integer.parseInt(id));
            }
            employeeService.deleteBatch(del_ids);
        }else {
            //当个删除
            employeeService.deleteEmpById(Integer.parseInt(ids));
        }


        return Msg.Success();
    }

}
